//
//  ACLog.swift
//  ACFrameworkSwift
//
//  Created by fisherman on 2021/9/2.
//

import Foundation

/// debug 级别的日志
public func ACLogDebug(_ message: String, tag: String = "", file: String = #file, line: Int = #line, funcName: String = #function) {
    ACLogBase(level: kLevelDebug, message: message, tag: tag, file: file, line: line, funcName: funcName, prefix: "【Debug】")
}

/// 通用信息流
public func ACLogInfo(_ message: String, tag: String = "", file: String = #file, line: Int = #line, funcName: String = #function) {
    ACLogBase(level: kLevelInfo, message: message, tag: tag, file: file, line: line, funcName: funcName, prefix: "【Info】")
}

/// 警告日志
public func ACLogWarning(_ message: String, tag: String = "", file: String = #file, line: Int = #line, funcName: String = #function) {
    ACLogBase(level: kLevelWarn, message: message, tag: tag, file: file, line: line, funcName: funcName, prefix: "【Warning】")
}

/// 错误日志
public func ACLogError(_ message: String, tag: String = "", file: String = #file, line: Int = #line, funcName: String = #function) {
    ACLogBase(level: kLevelError, message: message, tag: tag, file: file, line: line, funcName: funcName, prefix: "【Error】")
}

func ACLogBase(level: TLogLevel, message: String, tag: String, file: String, line: Int, funcName: String, prefix: String) {
    if XLogBridge.shouldLog(level) {
        let aMsg = prefix + message
        XLogBridge.log(with: level, tag: tag, fileName: file, lineNumber: Int32(line), funcName: funcName, message: aMsg)
    }
}


/**
 * 自定义 Log
 */
public class ACLog {
    
    public static var `default` = ACLog()
    public var logPath = ""
    
    #if (DEBUG)
    let maxLogSize: UInt64 = 1024
    #else
    let maxLogSize: UInt64 = 1024 * 1024 * 5 // 5 M
    #endif
    
    /// 默认的 log 存储路径
    var defaultLogPath: String {
        NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0].appending("/Logger")
    }
    
    /// 默认的 log 前缀
    var defaultNamePrefix: String {
        if let name = Bundle.main.object(forInfoDictionaryKey: "CFBundleDisplayName") as? String {
            return name
        }
        return ""
    }
    
    // MARK: - Init
    
    public init() {
        NotificationCenter.default.addObserver(self,
                                               selector: #selector(applicationWillTerminate),
                                               name: UIApplication.willTerminateNotification,
                                               object: nil)
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
    @objc
    private func applicationWillTerminate() {
        XLogBridge.close();
    }
    
    /// 初始化时的配置
    /// - Parameters:
    ///   - logPath: 日志路径，可不传默认配置到 "/Document/Logger/"
    ///   - pubkey: 公钥
    public func config(logPath: String = "", pubkey: String) {
        if logPath.isEmpty == false {
            self.logPath = logPath
        }else {
            self.logPath = defaultLogPath
        }
        
        var isDirectory: ObjCBool = false
        let isExist = FileManager.default.fileExists(atPath: self.logPath, isDirectory: &isDirectory)
        if isExist == false || isDirectory.boolValue == false {
            do {
                try FileManager.default.createDirectory(atPath: self.logPath, withIntermediateDirectories: true, attributes: nil)
            } catch {
                #if DEBUG
                print(error)
                #endif
                return
            }
        }
        
        XLogBridge.config(withLogPath: self.logPath, pubkey: pubkey, maxSize: maxLogSize, nameprefix: defaultNamePrefix)
    }
}
